package cn.ainit.sys.ds.store;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sun.org.apache.bcel.internal.classfile.Code;
import com.sun.org.apache.bcel.internal.generic.Select;

import cn.ainit.butn.proceduce.CommonProcedure;
import cn.ainit.common.ReturnObject;
import cn.ainit.sys.framework.entity.SysColumns;
import cn.ainit.sys.framework.save.ReceiveZM;
import cn.ainit.sys.menu.SessionCont;
import cn.ainit.sys.query.datastore.DataStore;
import cn.ainit.sys.query.entity.QueryJson;

@Controller
@RequestMapping("/store")
public class StoreController {

	private StoreService storeService;

	@Resource
	public void setStoreService(StoreService storeService) {
		this.storeService = storeService;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/storeList")
	@ResponseBody
	public List<Object> storeList(String dsId,HttpServletRequest request) throws Exception{
		try {
			String sql ="";
			List<Object> list = new ArrayList<Object>();
			//1.根据DsId去DataStore中查找相关的sql语句
			sql = storeService.findStore(dsId).getSqlText();
			//2.写根据sql查询list的方法
			list = (List<Object>) storeService.findObjects(sql);
			if (list != null && !list.equals("")) {
				return list;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	/***
	 * 通过dsId找到对应的DataStore 
	 * @param dsId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getStore")
	@ResponseBody
	public DataStore getStore(String dsId,HttpServletRequest request) throws Exception{
		try {
			DataStore ds=storeService.findStore(dsId);
			if (ds != null) {
				return ds;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/***
	 * 通用的审核操作方法
	 * @param dsId
	 * @param pkStr
	 * @param request
	 * @return
	 * author
	 * @throws Exception
	 */
	@RequestMapping("/commCheck")
	@ResponseBody
	public ReturnObject commCheck(String dsId,String pkStr,HttpServletRequest request) throws Exception{
		ReturnObject returnObject = new ReturnObject();
		String sql="";
		String[] pks=pkStr.split(";");
		for (int i = 0; i < pks.length; i++) {
			String[] temp=pks[i].split("-");
			if(i!=0){
				sql+=" and ";
			}
			for (int j = 0; j <temp.length; j++) {
				if(j!=0){
					sql=(sql+"='"+temp[j]+"' ");
				}else{
					sql=sql+temp[j]+" ";
				}
			}
		}
		//得到要跟新的那张表
		DataStore ds=getStore(dsId, request);
		String table=ds.getUpdateTable();

		//根据条件得到要跟新的表的选中数据的审核状态
		String hql1="select is_verify  from "+ table +" where "+sql;
		int is_verify=storeService.getIsVerify(hql1);
		String hql2="select is_destroy  from "+ table +" where "+sql;
		int destroy=storeService.getIsDestory(hql2);
		//首先检查数据是否作废
		
		if(destroy==1){
			returnObject.setMsg("该数据已经作废，不能进行审核");
		}else{
			//检查状态是否审核更新
			if(is_verify==0){
				try {
					//得到拼接后的sql语句
					//如果是书号与CIP信息（BJ_ISBN_CIP），中的XT_ID不能为空，否则不能跟新
					sql="update "+table+" set is_verify=1 where "+sql;
					int result=storeService.checkObject(sql);
					if (result>0) {
						returnObject.setMsg("审核成功");
					}else{
						returnObject.setMsg("审核失败");
					}
				} catch (Exception e) {
					e.printStackTrace();
					returnObject.setMsg("审核异常");
				}

			}else if(is_verify==1){
				returnObject.setMsg("该数据已经审核过");
			}else if(is_verify==2){
				returnObject.setMsg("正在审批阶段");
			}
		}
		
		return returnObject;

	}

	/**
	 * 通用的作废（包括某些执行存储过程的按钮）
	 * @param dsId
	 * @param butnCode
	 * @param pkStr
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-4-24 下午02:21:41
	 */
	@RequestMapping("/commDesOrApply")
	@ResponseBody
	public ReturnObject commDestory(String dsId,String butnCode,String pkStr,String aord,HttpServletRequest request,HttpSession session)throws Exception{
		ReturnObject returnObject = new ReturnObject();
		try {
			String[] dsIds = dsId.split(";");
			List<DataStore> list = new ArrayList<DataStore>();
			Boolean flag = false;
			String wheresql = "";
			String sql = "";
			//拼接条件语句
			String[] pks=pkStr.split(";");
			for (int i = 0; i < pks.length; i++) {
				String[] temp=pks[i].split("-");
				if(i!=0){
					wheresql+=" and ";
				}
				for (int j = 0; j <temp.length; j++) {
					if(j!=0){
						wheresql=(wheresql+"='"+temp[j]+"' ");
					}else{
						wheresql=wheresql+temp[j]+" ";
					}
				}
			}
			String manId ="";
			Object uid =session.getAttribute(SessionCont.uid);
			String stationId ="";
			String[] vals=pks[0].split("-");
			Object staId = session.getAttribute(SessionCont.STATION_ID);
			if(uid !=null){
				manId = uid.toString();
			}
			if(staId !=null){
				stationId =staId.toString();
			}
			//1.根据dsId 去Commen_procedure中查找是否有单独的存储过程要执行
			CommonProcedure commonProcedure = new CommonProcedure();
			commonProcedure = this.storeService.procedureByDsId(dsIds[0],butnCode);
			if (commonProcedure !=null) { //2.如果存在就去执行存储过程
//				returnObject.setInfo(aord);
				System.out.println("----------------------------进入存储过程");
				returnObject = this.storeService.execProcedure(vals[1],dsId,manId, stationId,commonProcedure.getProcedure());
			}else {//3.如果不存在就各自作废或审核   
				//判断父节点是否已经执行或者是父节点有没有
				//1.根据dsId 去查找flowID
//				String sql2 = "select flow_id from map_table_flowNode f where f.ds_id ='"+dsIds[0]+"' ";
//				String flowId = this.storeService.getStringBySql(sql2);
//				//2.根据flowId 去查找managerId
//				String sql3 = "select b.flow_id from bs_flowmanager b where b.flow_id = '"+flowId+"' and "+wheresql;
//				String managerId = this.storeService.getStringBySql(sql3);
//				//执行存储过程判断父节点
//				String retVal = this.storeService.execParentNode(managerId);
//				if(!"1".equals(retVal)){ //执行完成  父节点无碍
//					returnObject.setInfo(aord);
//					returnObject.setMsg(retVal);
//					return returnObject;
//				}
				flag = this.storeService.updDestory(dsId,manId,wheresql,aord);// aord 是判断审核还是作废的标志位
				if (flag){
					returnObject.setMsg("success");
				}else {
					returnObject.setMsg("error");
					returnObject.setErr("SQL语句不正确！当前表中缺少某些列");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnObject.setMsg("error");
			returnObject.setErr(e.getMessage());
		}
		returnObject.setInfo(aord);
		return returnObject;
	}






	/***
	 * 通用的审批操作方法(拆分得到表的主键的值)
	 * @param dsId
	 * @param pkStr
	 * @param request
	 * @return
	 * author
	 * @throws Exception
	 */
	@RequestMapping("/commApply")
	@ResponseBody
	public ReturnObject commApply(String pkStr,HttpServletRequest request){
		ReturnObject returnObject=new ReturnObject();
		List<String> pks=new ArrayList<String>();
		//查询得到表的主键值
		String[] pksValues=pkStr.split(";");
		for (int i = 0; i < pksValues.length; i++) {
			String[] temp=pksValues[i].split("-");
			for (int j = 0; j <temp.length; j++) {
				if(j!=0){
					pks.add(temp[j]);
				}		
			}
		}
		returnObject.setNameValue(pks);
		return returnObject;
	}

	
	/**************************
	 * 根据dsID 和主键的 的到单据的审核状态
	 * @param dsId
	 * @param pkStr
	 * @param request
	 * @return
	 * @throws Exception
	 */
	
	@RequestMapping("/judgeCheck")
	@ResponseBody
	public ReturnObject judgeCheck(String dsId,String pkStr,HttpServletRequest request) throws Exception{
		Integer is_verify=null;
		ReturnObject returnObject = new ReturnObject();
		//判断主键个数和 自动拼接的主键 parsePKStr个数是否一致
		String sql="";
		String[] pks=pkStr.split(";");
		for (int i = 0; i < pks.length; i++) {
			String[] temp=pks[i].split("-");
			if(i!=0){
				sql+=" and ";
			}
			for (int j = 0; j <temp.length; j++) {
				if(j!=0){
					sql=(sql+"='"+temp[j]+"' ");
				}else{
					sql=sql+temp[j]+" ";
				}
			}
		}
		//得到要跟新的那张表
		String table="";
		DataStore ds=getStore(dsId,request);
		try{
			table=ds.getUpdateTable();	
		}catch (Exception e) {
			e.printStackTrace();
		}
		//根据条件得到要跟新的表的选中数据的审核状态
		String hql2="select is_destroy  from "+ table +" where "+sql;
		int destroy=storeService.getIsDestory(hql2);
		hql2="select dj_code from "+table +" where "+sql;
		String djCode=storeService.getStringBySql(hql2);
		hql2="select dj_type from "+table +" where "+sql;
		String djType=storeService.getStringBySql(hql2);
		
		List<String> vals=new ArrayList<String>();
		vals.add(djCode);
		vals.add(djType);
		returnObject.setNameValue(vals);
		//单据已经作废时,不能进行审批
		if(destroy==1){
			returnObject.setMsg("fail");
			returnObject.setInfo("该单据已经作废不能进行审批");
		}else{
			returnObject.setMsg("success");
			String hql1="select is_verify  from "+ table +" where "+sql;
			is_verify=storeService.getIsVerify(hql1);
			returnObject.setTraState(is_verify);
		}
		return returnObject;
	}
	/**
	 * 根据sql 添加sys_columns
	 * @param sqlText
	 * @param dsId
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyy
	 * @date 2014-9-20 下午05:51:57
	 */
	@RequestMapping("/newColumns") 
	@ResponseBody
	public QueryJson newColumns(String sqlText,String dsId,HttpServletRequest request) throws Exception{
		QueryJson queryJson = new QueryJson();
		List<String> colnList = new ArrayList<String>();
		List queryCol = new ArrayList();
		try {
			boolean flag =false;
			colnList = storeService.callBackSql(sqlText);
			flag = storeService.saveQueryCol(colnList, dsId);
			if (flag) {
				String sql = "SELECT * FROM SYS_COLUMNS WHERE DS_ID ='"+dsId+"'";
				queryCol = storeService.execSql(sql);
			}
			queryJson.setRows(queryCol);//rows
		}catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}
	/**
	 * 可视化界面中的保存datagrid的方法
	 * @param receiveZMobj
	 * @param request
	 * @param session
	 * @return
	 * @author wyy
	 * @date 2014-9-23 上午09:40:57
	 */
	@RequestMapping("/saveConfigPage")
	@ResponseBody
	public ReturnObject saveConfigPage(@RequestBody Map<String,Object> receiveMobj,HttpServletRequest request,HttpSession session){
		//zmReceiveObj   //receiveObjs
		
		ReturnObject returnObject = new ReturnObject();
		try {
			returnObject = this.storeService.saveConfig(receiveMobj);
		} catch (Exception e) {
			e.printStackTrace();
			returnObject.setMsg("error");
			returnObject.setInfo(e.getMessage());
		}
		return returnObject;
	}
}
